package com.song.elasticsearch.config.redis;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @description:
 * @author: guangyang
 * @time: 2024/3/5 14:50
 */

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
    private String url = "localhost:6379";
    private int maxTotal;
    private int maxIdle;
    private int maxWaitMillis;
    private int timeout;
    private int maxAttempts;
    private boolean ssl;
    private String krbConfFile;
    private String userKeyTableFile;
    private String userPrincipal;
    private String serverConfigPath;

    private boolean redisSign;
    private boolean isSecurityMode;

    public JedisPoolConfig getJedisPoolConfig(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        // 最大连接数
        poolConfig.setMaxTotal(maxTotal);
        // 最大空闲数
        poolConfig.setMaxIdle(maxIdle);
        // 最大允许等待时间，如果超过这个时间还未获取到连接，则会报JedisException异常：
        poolConfig.setMaxWaitMillis(maxWaitMillis);
        return poolConfig;
    }

    public void securityAuth(){
        String krbConf = configPath() + krbConfFile;
        String userKeyTable = configPath() + userKeyTableFile;
        try {
            LoginUtil.setKrb5Config(krbConf);
            LoginUtil.setJaasFile(userPrincipal, userKeyTable);
        } catch (IOException e) {
            log.error("Redis认证失败：" + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Bean
    public JedisCluster jedisCluster(){
        if (!redisSign){
            securityAuth();
            redisSign = true;
        }
        return getJedisCluster();
    }

    public JedisCluster getJedisCluster(){
        String[] urls = url.split(",");
        Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
        for (String url : urls) {
            String[] ipAndPort = url.split(":");
            String ip = ipAndPort[0];
            String port = ipAndPort[1];
            nodes.add(new HostAndPort(ip, Integer.valueOf(port)));
        }
        try {
//                final SSLSocketFactory socketFactory = SslSocketFactoryUtil.createTrustALLSslSocketFactory();
            return new JedisCluster(nodes, timeout, maxAttempts, getJedisPoolConfig());
//                cluster = new JedisCluster(nodes, timeout, timeout, maxAttempts,"","", getJedisPoolConfig(), ssl, socketFactory, null, null, null);
        } catch (Exception e) {
            log.error("Redis创建集群连接失败：" + e.getMessage());
        }
        return null;
    }

    public String configPath(){
        String configPath = "";
        try {
            configPath = ResourceUtils.getURL("classpath:").getPath();
            configPath = URLDecoder.decode(configPath, "UTF-8");
            if (System.getProperty("os.name").toLowerCase().contains("win")){
                configPath = configPath.substring(1).replace("/", "\\");
            }else{
                configPath = serverConfigPath;
            }
            log.info("Redis读取配置路径为：configPath=====>" + configPath);
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            log.error(e.getMessage());
        }
        return configPath;
    }
}
